package main

import (
	"fmt"
	"os"
)

//加载迷宫文件
func readMaze(filename string) [][]int {
	file, err := os.Open(filename)
	if err != nil {
		panic(err)
	}

	var row, col int
	fmt.Fscanf(file, "%d %d", &row, &col)

	maze := make([][]int, row) //注意，这里表示有多少个[]int, row填的是第一个[]
	for i := range maze {
		maze[i] = make([]int, col)
		for j := range maze[i] {
			fmt.Fscanf(file, "%d", &maze[i][j])
		}
	}

	return maze
}

//定义数据点
type point struct {
	i, j int
}

//声明4个方向
var dirs = [4]point{
	{-1, 0}, //上
	{0, -1}, //左
	{1, 0},  //下
	{0, 1},  //右
}

func (p point) add(r point) point {
	return point{p.i + r.i, p.j + r.j}
}

func (p point) at(grid [][]int) (int, bool) {
	//上、下越界（行越界）
	if p.i < 0 || p.i >= len(grid) {
		return 0, false
	}
	//左、右越界（列越界）
	if p.j < 0 || p.j >= len(grid[p.i]) {
		return 0, false
	}
	return grid[p.i][p.j], true
}

//走迷宫
//点的三种状态：未发现，已发现未探索，已发现已探索
//退出条件：（1）走到了终点（2）没有未探索的点了。2者其一即可
func walk(maze [][]int, start, end point) [][]int {
	// 创建容器，记录走过路径(记录步骤数)
	steps := make([][]int, len(maze))
	for i := range steps {
		steps[i] = make([]int, len(maze[i]))
	}

	// 创建容器，记录待探索的点
	Q := []point{start}

	// 开始探索，没有未探索的点了退出
	for len(Q) > 0 {
		cur := Q[0]
		Q = Q[1:]

		//发现终点退出
		if cur == end {
			break
		}

		//沿着4个方向探索
		for _, dir := range dirs {
			next := cur.add(dir)

			//maze at next is 0 and steps at next is 0 and next!=start
			//就是说，可以探索，并且未被探索过。由于起始值是0，为了不走回去，所以额外规定next!=start
			val, ok := next.at(maze)
			//上面maze at next is 0条件取反
			if !ok || val == 1 {
				continue
			}

			val, ok = next.at(steps)
			//上买steps at next is 0取反
			if !ok || val != 0 { //说明走过了
				continue
			}

			//回到起点
			if next == start {
				continue
			}

			//记录步骤数
			curSteps, _ := cur.at(steps)
			steps[next.i][next.j] = curSteps + 1
			//将新的点加到待探索队列
			Q = append(Q, next)
		}

	}

	return steps

}

func main() {
	maze := readMaze("chapter12-maze/maze/maze.in")

	// 打印下迷宫
	//for _, row := range maze {
	//	for _, val := range row {
	//		fmt.Printf("%d ", val)
	//	}
	//	fmt.Println()
	//}

	steps := walk(maze, point{0, 0}, point{len(maze) - 1, len(maze[0]) - 1})

	// 打印探索步骤
	for _, row := range steps {
		for _, val := range row {
			fmt.Printf("%3d ", val)
		}
		fmt.Println()
	}
}
